import { createReducer, createActions } from 'reduxsauce'
import Immutable from 'seamless-immutable'

/* ------------- Types and Action Creators ------------- */

const { Types, Creators } = createActions({
  orderDetailRequest: ['id', 'token'],
  orderDetailSuccess: ['payload'],
  orderDetailFailure: null,
  cancelRequest: ['id', 'token'],
  cancelSuccess: ['payload'],
  cancelFailure: null,
  orderDeleteRequest: ['id', 'token'],
  orderDeleteSuccess: null,
  orderDeleteFailure: null,
})

export const OrderDetailTypes = Types
export default Creators

/* ------------- Initial State ------------- */

export const INITIAL_STATE = Immutable({
  id: null,
  fetching: null,
  deleteFetching: null,
  payload: null,
  error: null
})

/* ------------- Reducers ------------- */
// request the data from an api
export const request = (state, { id, token }) =>
  state.merge({ fetching: true, error:null, id })

// successful api lookup
export const success = (state, action) => {
  const { payload } = action
  return state.merge({ fetching: false, error: null, payload })
}

// Something went wrong somewhere.
export const failure = state =>
  state.merge({ fetching: false, error: true, payload: null })

export const cancelRequest = (state) =>
  state.merge({fetching:true, error:null})

export const cancelSuccess = (state, {payload}) =>
  state.merge({fetching:false, error:null, payload})

export const cancelFailure = (state) =>
  state.merge({fetching:false,error:true})

export const deleteRequest = (state) =>
  state.merge({deleteFetching:true, error:null})

export const deleteSuccess = (state) => INITIAL_STATE

export const deleteFailure = (state) =>
  state.merge({deleteFetching:false,error:true})

/* ------------- Hookup Reducers To Types ------------- */

export const reducer = createReducer(INITIAL_STATE, {
  [Types.ORDER_DETAIL_REQUEST]: request,
  [Types.ORDER_DETAIL_SUCCESS]: success,
  [Types.ORDER_DETAIL_FAILURE]: failure,
  [Types.CANCEL_REQUEST]: cancelRequest,
  [Types.CANCEL_SUCCESS]: cancelSuccess,
  [Types.CANCEL_FAILURE]: cancelFailure,
  [Types.ORDER_DELETE_REQUEST]: deleteRequest,
  [Types.ORDER_DELETE_SUCCESS]: deleteSuccess,
  [Types.ORDER_DELETE_FAILURE]: deleteFailure,
})
